//
//  CollectionDetailViewController.m
//  Tang
//
//  Created by 邓芮 on 15/12/7.
//  Copyright © 2015年 352324497@qq.com. All rights reserved.
//

#import "CollectionDetailViewController.h"
#import "CollectionDetailFirstCell.h"
#import "CollectionDetailTableViewCell.h"
#import "CollectionDetailHeaderViewCell.h"

#import "CollectionDetailHeaderViewModel.h"
#import "CollectionDetailCellModel.h"

#import "RecommendDetailController.h"
#import "UMSocial.h"
#import "UMSocialQQHandler.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialSinaSSOHandler.h"
@interface CollectionDetailViewController ()<UITableViewDataSource, UITableViewDelegate>
// 最上面的cell的model
@property (nonatomic, strong) CollectionDetailHeaderViewModel *headerModel;
// 最新的model数组
@property (nonatomic, strong) NSMutableArray *firstModelArray;
// 精选的model数组
@property (nonatomic, strong) NSMutableArray *nextModelArray;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) BOOL isFirst;
@property (nonatomic, assign) NSInteger firstNum;
@property (nonatomic, assign) NSInteger nextNum;
@end

static NSString *firstCellIdentifier = @"cell1";
static NSString *detailCellIdentifier = @"cell2";
static NSString *headerViewIdentifier = @"header";
@implementation CollectionDetailViewController

- (NSMutableArray *)firstModelArray
{
    if (!_firstModelArray)
    {
        self.firstModelArray = [NSMutableArray array];
    }
    return _firstModelArray;
}

- (NSMutableArray *)nextModelArray
{
    if (!_nextModelArray)
    {
        self.nextModelArray = [NSMutableArray array];
    }
    return _nextModelArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIButton *rightBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 25, 25);
    [rightBtn setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem=[[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem=rightItem;
    
    self.navigationItem.title = @"每日一晒";
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KWidth, KHeight - 64) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[CollectionDetailFirstCell class] forCellReuseIdentifier:firstCellIdentifier];
    [self.tableView registerClass:[CollectionDetailTableViewCell class] forCellReuseIdentifier:detailCellIdentifier];
    [self.tableView registerClass:[CollectionDetailHeaderViewCell class] forHeaderFooterViewReuseIdentifier:headerViewIdentifier];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    
    self.isFirst = YES;
    self.firstNum = 0;
    self.nextNum = 0;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        NSString *string = [NSString stringWithFormat:@"app_installtime=1449036721.708244&app_versions=5.0&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&oauth_token=c6ed8d108659f067da486970ca4b3aad&subject_id=%@&v=8", self.Id];
        NSURL *url = [NSURL URLWithString:@"http://open3.bantangapp.com/community/subject/info"];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request setHTTPMethod:@"POST"];
        [request setHTTPBody:[string dataUsingEncoding:NSUTF8StringEncoding]];

        [self networkRequestWith:request];
        
        [self.firstModelArray removeAllObjects];
        [self.nextModelArray removeAllObjects];
        NSString *string1 = [NSString stringWithFormat:@"app_installtime=1449036721.708244&app_versions=5.0.1&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&oauth_token=c6ed8d108659f067da486970ca4b3aad&os_versions=9.1&page=0&pagesize=10&screensize=%0.f&subject_id=%@&track_deviceid=724D868E-D23A-4A92-902C-909AB20FB585&type_id=0&v=8", KWidth, self.Id];
        NSURL *url1 = [NSURL URLWithString:@"http://open3.bantangapp.com/community/subject/listPost"];
        NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url1];
        [request1 setHTTPMethod:@"POST"];
        [request1 setHTTPBody:[string1 dataUsingEncoding:NSUTF8StringEncoding]];
        [self requestDataCellWithRequest:request1];
        
        NSString *string2 = [NSString stringWithFormat:@"app_installtime=1449036721.708244&app_versions=5.0.1&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&oauth_token=c6ed8d108659f067da486970ca4b3aad&os_versions=9.1&page=0&pagesize=10&screensize=%0.f&subject_id=%@&track_deviceid=724D868E-D23A-4A92-902C-909AB20FB585&type_id=1&v=8", KWidth, self.Id];
        NSURL *url2 = [NSURL URLWithString:@"http://open3.bantangapp.com/community/subject/listPost"];
        NSMutableURLRequest *request2 = [NSMutableURLRequest requestWithURL:url2];
        [request2 setHTTPMethod:@"POST"];
        [request2 setHTTPBody:[string2 dataUsingEncoding:NSUTF8StringEncoding]];
        [self requsetBestWithRequest:request2];
        
        [self.tableView.mj_header endRefreshing];
    }];
    
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        if (self.isFirst)
        {
            self.firstNum += 1;
            NSString *string1 = [NSString stringWithFormat:@"app_installtime=1449036721.708244&app_versions=5.0.1&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&oauth_token=c6ed8d108659f067da486970ca4b3aad&os_versions=9.1&page=%ld&pagesize=10&screensize=%0.f&subject_id=%@&track_deviceid=724D868E-D23A-4A92-902C-909AB20FB585&type_id=0&v=8",(long)self.firstNum, KWidth, self.Id];
            NSURL *url1 = [NSURL URLWithString:@"http://open3.bantangapp.com/community/subject/listPost"];
            NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url1];
            [request1 setHTTPMethod:@"POST"];
            [request1 setHTTPBody:[string1 dataUsingEncoding:NSUTF8StringEncoding]];
            [self requestDataCellWithRequest:request1];
        }
        else
        {
            self.nextNum += 1;
            NSString *string2 = [NSString stringWithFormat:@"app_installtime=1449036721.708244&app_versions=5.0.1&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&oauth_token=c6ed8d108659f067da486970ca4b3aad&os_versions=9.1&page=%ld&pagesize=10&screensize=%0.f&subject_id=%@&track_deviceid=724D868E-D23A-4A92-902C-909AB20FB585&type_id=1&v=8", (long)self.nextNum, KWidth,self.Id];
            NSURL *url2 = [NSURL URLWithString:@"http://open3.bantangapp.com/community/subject/listPost"];
            NSMutableURLRequest *request2 = [NSMutableURLRequest requestWithURL:url2];
            [request2 setHTTPMethod:@"POST"];
            [request2 setHTTPBody:[string2 dataUsingEncoding:NSUTF8StringEncoding]];
            [self requsetBestWithRequest:request2];
        }
        [self.tableView.mj_footer endRefreshing];
    }];
}

- (void)networkRequestWith:(NSMutableURLRequest *)request
{
    [[NetworkState shareInstance]reachablityStatesWithDongHua:self];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data == nil)
        {
            [[NetworkState shareInstance] finshYYToVc:self];
            UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲, 网络好像不是很给力哦~~~" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *OKaction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            [alertView addAction:OKaction];
            [self presentViewController:alertView animated:YES completion:nil];
            return;
        }
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.headerModel = [CollectionDetailHeaderViewModel JsonWithDic:dic];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            [[NetworkState shareInstance]finshYYToVc:self];
        });
    }];
    [task resume];
    
}

- (void)requestDataCellWithRequest:(NSMutableURLRequest *)requset
{
    [[[NSURLSession sharedSession] dataTaskWithRequest:requset completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data == nil)
        {
            [[NetworkState shareInstance] finshYYToVc:self];
            UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲, 网络好像不是很给力哦~~~" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *OKaction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            [alertView addAction:OKaction];
            [self presentViewController:alertView animated:YES completion:nil];
            return;
        }
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        self.firstModelArray = [CollectionDetailCellModel JsonWithDic:dic modelArray:self.firstModelArray];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            [[NetworkState shareInstance]finshYYToVc:self];
        });
    }] resume];
    
    
}

- (void)requsetBestWithRequest:(NSMutableURLRequest *)request
{
    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data == nil)
        {
            [[NetworkState shareInstance] finshYYToVc:self];
            UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲, 网络好像不是很给力哦~~~" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *OKaction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            [alertView addAction:OKaction];
            [self presentViewController:alertView animated:YES completion:nil];
            return;
        }

        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        self.nextModelArray = [CollectionDetailCellModel JsonWithDic:dic modelArray:self.nextModelArray];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            [[NetworkState shareInstance]finshYYToVc:self];
        });
    }] resume];
}

- (void)rightBtnAction:(UIButton *)button
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5668e3bde0f55a90700038ed"
                                      shareText:@"推荐好物, 分享视频 https://itunes.apple.com/cn/app/%e7%b3%96%e5%a6%86/id1068451018?mt=8"
                                     shareImage:[UIImage imageNamed:@"Tango"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatTimeline, UMShareToWechatSession, UMShareToEmail, UMShareToSms,nil] delegate:nil];
}

//实现回调方法（可选）：
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.headerModel == nil)
    {
        return 0;
    }
    else
    {
        if (section == 0)
        {
            return 1;
        }
        else
        {
            if (self.isFirst)
            {
                return self.firstModelArray.count;
            }
            else
            {
                return self.nextModelArray.count;
            }
        }
    }
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        CollectionDetailFirstCell *cell = [tableView dequeueReusableCellWithIdentifier:firstCellIdentifier forIndexPath:indexPath];
        cell.model = self.headerModel;
        return cell;
    }
    else
    {
         CollectionDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:detailCellIdentifier forIndexPath:indexPath];
        
        if (self.isFirst)
        {
           CollectionDetailCellModel *model = self.firstModelArray[indexPath.row];
            [cell setModel:model tag:1000];
//            cell.model = model;
        }
        else
        {
            CollectionDetailCellModel *model = self.nextModelArray[indexPath.row];
            [cell setModel:model tag:1000];
//            cell.model = model;
        }
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        return [CollectionDetailFirstCell heightForFirstCell:self.headerModel];
    }
    else
    {
        if (self.isFirst)
        {
            return [CollectionDetailTableViewCell heightForCell:self.firstModelArray[indexPath.row] tag:1000];
        }
        else
        {
            return [CollectionDetailTableViewCell heightForCell:self.nextModelArray[indexPath.row] tag:1000];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 0;
    }
    return [CollectionDetailHeaderViewCell heightForHeader];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    CollectionDetailHeaderViewCell *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerViewIdentifier];
    [headerView.best addTarget:self action:@selector(bestAction:) forControlEvents:UIControlEventTouchUpInside];
    [headerView.lastest addTarget:self action:@selector(lastestAction:) forControlEvents:UIControlEventTouchUpInside];
    return headerView;
}

// 精选
- (void)bestAction:(UIButton *)button
{
    self.isFirst = NO;
    [self.tableView reloadData];
    [self scrollViewDidScrollToTop:self.tableView];
}

// 最新
- (void)lastestAction:(UIButton *)button
{
    self.isFirst = YES;
    [self.tableView reloadData];
    [self scrollViewDidScrollToTop:self.tableView];
}

- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
{
    if ([self.tableView contentOffset].y >= [CollectionDetailFirstCell heightForFirstCell:self.headerModel])
    {
         [self.tableView setContentOffset:CGPointMake(0, [CollectionDetailFirstCell heightForFirstCell:self.headerModel]) animated:YES];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    RecommendDetailController *recomViewVc = [[RecommendDetailController alloc]init];
    if (indexPath.section == 1)
    {
        if (self.isFirst)
        {
            CollectionDetailCellModel *model = self.firstModelArray[indexPath.row];
            recomViewVc.Id = model.Id;
        }
        else
        {
            CollectionDetailCellModel *model = self.nextModelArray[indexPath.row];
            recomViewVc.Id = model.Id;
        }
        [self.navigationController pushViewController:recomViewVc animated:NO];
    }
  
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
